import { Application } from 'egg';
import * as pageFindPlugin from 'mongoose-paginate';
import { GenderType, MemberType, GenderNameList } from '../constants';
import * as moment from 'moment';
import isPositiveInt from '../validator';

/**
 * 保洁会员集合
 */
export default (app: Application) => {
  const mongoose = app.mongoose;
  const ObjectId = mongoose.Schema.Types.ObjectId;
  const cleanmemberSchema = new mongoose.Schema({
    // 门店Id
    siteId: {
      type: ObjectId,
      required: true,
    },
    // 用户Id
    userId: {
      type: ObjectId,
      required: true,
    },
    // 电话号码
    phoneNumber: {
      type: Number,
      required: false,
    },
    // 姓名
    name: {
      type: String,
      required: false,
    },
    // 性别
    gender: {
      type: Number,
      required: false,
      enum: [ GenderType.female, GenderType.male ],
    },
    // 生日
    birthday: {
      type: Date,
      required: false,
    },
    // 余额(单位分)
    balance: {
      type: Number,
      default: 0,
      required: true,
      validate: isPositiveInt,
    },
    // 押金(不退还的)
    deposit: {
      type: Number,
      required: true,
      default: 0,
      validate: isPositiveInt,
    },
    // 会员类型
    memberType: {
      type: Number,
      required: true,
      enum: [ MemberType.reCharge, MemberType.deposit ],
    },
  }, { timestamps: true, toJSON: { virtuals: true, getters: true } });

  // 年龄
  // tslint:disable-next-line:ter-prefer-arrow-callback
  cleanmemberSchema.virtual('age').get(function (this: any) {
    return moment(this.birthday, 'YYYY-MM-DD').fromNow();
  });

  // 性别
  // tslint:disable-next-line:ter-prefer-arrow-callback
  cleanmemberSchema.virtual('genderName').get(function (this: any) {
    return GenderNameList[this.gender];
  });

  cleanmemberSchema.index({ userId: 1, siteId: 1 });
  cleanmemberSchema.plugin(pageFindPlugin, {});
  return mongoose.model('Cleanmember', cleanmemberSchema);
};
